package com.rw.pay.service.impl;

import com.rw.common.entity.DollarInfo;
import com.rw.common.entity.Receive;
import com.rw.pay.mapper.DollarInfoMapper;
import com.rw.pay.mapper.ReceiveMapper;
import com.rw.pay.service.ReceiveService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

/**
 * <p>
 * 领取表 服务实现类
 * </p>
 *
 * @author Rabit
 * @since 2021-12-20
 */
@Service
public class ReceiveServiceImpl extends ServiceImpl<ReceiveMapper, Receive> implements ReceiveService {


    @Autowired
    private DollarInfoMapper dollarInfoMapper;
    @Override
    public boolean getReceiveByUser(Receive receive) {
        //接收到的参数：用户信息id
        // TODO: 2021/12/21  校验用户信息是否正确，在真实的情况下,需要校验用户是否登录
        //优惠券信息id
        // TODO: 2021/12/21 校验优惠券的信息：是否过期，
        //  校验优惠券的数量，是否可以开始抢购优惠券
       DollarInfo dollarInfo = dollarInfoMapper.selectById(receive.getDid());
        System.out.println("从数据库中查询出来的优惠券信息："+dollarInfo);
        // TODO: 2021/12/21 加上一个校验：同一个用户只能抢购一张券
       if (dollarInfo.getStartTime().compareTo(LocalDateTime.now())< 0 &&dollarInfo.getEndTime().compareTo(LocalDateTime.now())> 0 &&dollarInfo.getNum() > 0){
           System.out.println("优惠券满足抢购条件");
           // TODO: 2021/12/21 当所有的校验都通过以后，
           //  优惠券的抢购信息插入数据，并且优惠券数量减一
           DollarInfo up = new DollarInfo();
           up.setId(dollarInfo.getId());
           up.setNum(dollarInfo.getNum() - 1);
           int i = dollarInfoMapper.updateById(up);
           System.out.println("更新库存的结果"+i);
           if (i > 0){
               // TODO: 2021/12/21 如果库存修改成功后，把信息放入数据库中
               receive.setCreateTime(LocalDateTime.now());
                int insert = baseMapper.insert(receive);
               return insert > 0;
           }

       }
        return false;
    }
}
